#!/usr/bin/env python3
"""
K716数据处理脚本（专业版）
使用专业SVG生成器，参考K717的效果
"""

import sys
import os
import json
import math
from pathlib import Path
from datetime import datetime

# 添加当前目录到Python路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

# 导入增强版处理器和专业SVG生成器
from enhanced_ploop_processor import EnhancedPLoopProcessor, Vertex
from generate_professional_svg import generate_professional_svg

def calculate_path_statistics(vertices):
    """计算路径统计信息"""
    if len(vertices) < 2:
        return {}
    
    total_perimeter = 0
    min_edge = float('inf')
    max_edge = 0
    
    for i in range(len(vertices)):
        current = vertices[i]
        next_vertex = vertices[(i + 1) % len(vertices)]
        edge_length = current.distance_to(next_vertex)
        
        total_perimeter += edge_length
        min_edge = min(min_edge, edge_length)
        max_edge = max(max_edge, edge_length)
    
    return {
        "perimeter": total_perimeter,
        "shortest_edge": min_edge,
        "longest_edge": max_edge
    }

def main():
    """主处理函数"""
    
    # 输入和输出路径
    input_file = Path("test-data/1KA-ARCH-P-R-K716.txt")
    output_dir = Path("results_k716_professional")
    
    # 确保输出目录存在
    output_dir.mkdir(exist_ok=True)
    
    print(f"开始专业处理K716数据...")
    print(f"输入文件: {input_file}")
    print(f"输出目录: {output_dir}")
    
    # 检查输入文件是否存在
    if not input_file.exists():
        print(f"错误：输入文件 {input_file} 不存在")
        return False
    
    try:
        # 创建增强版处理器实例
        processor = EnhancedPLoopProcessor(tolerance=0.1)
        
        # 读取文件内容
        with open(input_file, 'r', encoding='utf-8') as f:
            content = f.read()
        
        print(f"✅ 文件读取成功，内容长度: {len(content)} 字符")
        
        # 解析PLOOP数据
        print("\n正在解析PLOOP数据...")
        ploops = processor.parse_file(content)
        print(f"✅ 解析完成，发现 {len(ploops)} 个PLOOP")
        
        # 查找K716 PLOOP
        k716_ploop = None
        for ploop in ploops:
            if 'K716' in ploop.name:
                k716_ploop = ploop
                break
        
        if k716_ploop is None:
            print("❌ 错误: 没有找到K716 PLOOP")
            return False
        
        print(f"\n✅ 找到K716: {k716_ploop}")
        
        # 增强处理
        print("\n正在进行增强处理...")
        processed_vertices = processor.process_ploop_enhanced(k716_ploop)
        
        # 计算统计信息
        stats = calculate_path_statistics(processed_vertices)
        
        # 生成处理报告
        current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        original_count = len(k716_ploop.vertices)
        processed_count = len(processed_vertices)
        fradius_count = sum(1 for v in processed_vertices if v.fradius)
        optimization_rate = ((original_count - processed_count) / original_count * 100) if original_count > 0 else 0
        
        report = {
            "input_file": str(input_file),
            "processing_timestamp": current_time,
            "original_vertices": original_count,
            "processed_vertices": processed_count,
            "fradius_vertices": fradius_count,
            "optimization_rate": optimization_rate,
            "perimeter": stats.get("perimeter", 0),
            "shortest_edge": stats.get("shortest_edge", 0),
            "longest_edge": stats.get("longest_edge", 0)
        }
        
        # 保存处理报告
        report_file = output_dir / "k716_professional_report.json"
        with open(report_file, 'w', encoding='utf-8') as f:
            json.dump(report, f, indent=2, ensure_ascii=False)
        
        print(f"\n=== K716 专业处理结果 ===")
        print(f"原始顶点数: {report['original_vertices']}")
        print(f"处理后顶点数: {report['processed_vertices']}")
        print(f"FRADIUS顶点数: {report['fradius_vertices']}")
        print(f"优化率: {report['optimization_rate']:.1f}%")
        print(f"周长: {report['perimeter']:.2f}mm")
        print(f"最短边: {report['shortest_edge']:.3f}mm")
        print(f"最长边: {report['longest_edge']:.2f}mm")
        
        # 生成专业SVG文件
        svg_file = output_dir / "k716_professional.svg"
        svg_content = generate_professional_svg(
            processed_vertices,
            title="PLOOP Profile: K716",
            height_mm=k716_ploop.height
        )
        
        with open(svg_file, 'w', encoding='utf-8') as f:
            f.write(svg_content)
        
        print(f"\n📊 专业SVG文件已生成: {svg_file}")
        print(f"   - 包含完整坐标系统和网格")
        print(f"   - 详细的顶点坐标表")
        print(f"   - 工程图纸风格布局")
        print(f"   - FRADIUS圆弧标记")
        
        # 生成详细分析报告
        analysis_file = output_dir / "k716_professional_analysis.md"
        with open(analysis_file, 'w', encoding='utf-8') as f:
            f.write(f"# K716 专业处理分析报告\n\n")
            f.write(f"## 基本信息\n")
            f.write(f"- 输入文件: {input_file}\n")
            f.write(f"- 处理时间: {current_time}\n")
            f.write(f"- 处理器版本: Enhanced PLOOP Processor (Professional)\n")
            f.write(f"- SVG风格: 工程图纸风格（参考K717效果）\n\n")
            
            f.write(f"## 处理统计\n")
            f.write(f"- 原始顶点数: {report['original_vertices']}\n")
            f.write(f"- 处理后顶点数: {report['processed_vertices']}\n")
            f.write(f"- FRADIUS顶点数: {report['fradius_vertices']}\n")
            f.write(f"- 优化率: {report['optimization_rate']:.1f}%\n\n")
            
            f.write(f"## 几何分析\n")
            f.write(f"- 总周长: {report['perimeter']:.2f}mm\n")
            f.write(f"- 最短边长: {report['shortest_edge']:.3f}mm\n")
            f.write(f"- 最长边长: {report['longest_edge']:.2f}mm\n")
            f.write(f"- PLOOP高度: {k716_ploop.height:.1f}mm\n\n")
            
            f.write(f"## 专业SVG特性\n")
            f.write(f"- ✅ 完整的XY坐标系统\n")
            f.write(f"- ✅ 精确的刻度标记\n")
            f.write(f"- ✅ 专业网格线系统\n")
            f.write(f"- ✅ 详细的顶点坐标表\n")
            f.write(f"- ✅ FRADIUS圆弧可视化\n")
            f.write(f"- ✅ 工程图纸风格布局\n\n")
            
            f.write(f"## 处理后顶点详情\n")
            f.write(f"| 编号 | X坐标 | Y坐标 | Z坐标 | FRADIUS |\n")
            f.write(f"|------|-------|-------|-------|----------|\n")
            for i, v in enumerate(processed_vertices):
                frad_str = f"{v.fradius:.2f}mm" if v.fradius else "-"
                f.write(f"| {i} | {v.x:.2f} | {v.y:.2f} | {v.z:.2f} | {frad_str} |\n")
            
            f.write(f"\n## 文件输出\n")
            f.write(f"- 专业SVG: k716_professional.svg\n")
            f.write(f"- 处理报告: k716_professional_report.json\n")
            f.write(f"- 分析报告: k716_professional_analysis.md\n")
        
        print(f"📋 分析报告已生成: {analysis_file}")
        print(f"💾 处理报告已保存: {report_file}")
        
        return True
        
    except Exception as e:
        print(f"处理过程中发生错误: {e}")
        import traceback
        traceback.print_exc()
        return False

if __name__ == "__main__":
    success = main()
    if success:
        print("\n✅ K716专业处理完成！")
        print("📊 请在浏览器中打开SVG文件查看专业效果")
    else:
        print("\n❌ K716专业处理失败！")
        sys.exit(1) 